package com.nuoniu.sibanyun.service.production.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.bo.UnExecutedBo;
import com.nuoniu.sibanyun.entity.production.VProductionWorkDetail;
import com.nuoniu.sibanyun.entity.production.VProductionWorkInventoryDetail;
import com.nuoniu.sibanyun.entity.production.VProductionWorkMain;
import com.nuoniu.sibanyun.mapper.production.VProductionWorkInventoryDetailMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkInventoryDetailService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  加工单-材料明细 服务实现类
 * </p>
 *
 * @author 白强
 * @since 2021-03-20
 */
@Service
public class VProductionWorkInventoryDetailServiceImpl extends ServiceImpl<VProductionWorkInventoryDetailMapper, VProductionWorkInventoryDetail> implements IVProductionWorkInventoryDetailService {

    @Autowired
    private IErpAccountService accountService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchSave(VProductionWorkMain productionWorkMain, List<Long> detailIds) {
        Integer currentAccountId = accountService.getCurrentAccountId();
        Long mainId = productionWorkMain.getId();
        UserInfo userInfo = UserThreadLocal.get();


        List<VProductionWorkInventoryDetail> allInventoryDetailList = new ArrayList<>();
        List<VProductionWorkDetail> orderDetailList = productionWorkMain.getOrderDetailList();
        Set<Long> notDeleteInventDetailIds = new HashSet<>();
        orderDetailList.forEach(detail->{
            Long detailId = detail.getId();
            List<VProductionWorkInventoryDetail> productionWorkInventoryDetailList = detail.getProductionWorkInventoryDetailList();
            if ( productionWorkInventoryDetailList.stream().anyMatch(f->null == f.getInventoryId()) )throw new NuoNiuException("请选择物料");
            if(productionWorkInventoryDetailList.size() == 0)throw new NuoNiuException("产品明细："+detail.getInventoryName() + " 的材料明细 不能为空");
            //删除 剩余产品明细中更换的 材料明细
            if(detailIds.contains(detailId)){
                productionWorkInventoryDetailList.forEach(inventoryDetail -> {
                    if(null != inventoryDetail.getId()){
                        notDeleteInventDetailIds.add(inventoryDetail.getId());
                    }
                });
            }
            productionWorkInventoryDetailList.forEach(inventoryDetail->{
                if (detail.getInventoryId().equals(inventoryDetail.getInventoryId()))throw new NuoNiuException("产品明细："+detail.getInventoryName() + " 的材料明细中，包含产品本身");
                inventoryDetail.setCompanyId(detail.getCompanyId());
                inventoryDetail.setAccountId(detail.getAccountId());
                inventoryDetail.setProductionWorkMainId(mainId.intValue());
                inventoryDetail.setProductionWorkDetailId(detailId.intValue());
                inventoryDetail.setDataSource(productionWorkMain.getDataSource());
                allInventoryDetailList.add(inventoryDetail);
            });
        });
        //1.根据 加工单 产品明细的ID 删除 材料明细
        if (null != detailIds && detailIds.size() > 0){
            QueryWrapper<VProductionWorkInventoryDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("company_id",userInfo.getCompanyId());
            queryWrapper.eq("account_id",currentAccountId);
            queryWrapper.eq("production_work_main_id",mainId);
            if(notDeleteInventDetailIds.size() > 0){
                queryWrapper.and(wrapper->wrapper.notIn("production_work_detail_id",detailIds)
                        .or(wrapper2->wrapper2.in("production_work_detail_id",detailIds).and(wrapper3->wrapper3.notIn("id",notDeleteInventDetailIds))));
            }
            remove(queryWrapper);
        }
        //2.保存 材料明细
        if (allInventoryDetailList.size() > 0){
            saveOrUpdateBatch(allInventoryDetailList);
        }
    }

    @Override
    public List<VProductionWorkInventoryDetail> listByProductionDispatchId(Long dispatchId) {
        Integer currentAccountId = accountService.getCurrentAccountId();
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<VProductionWorkInventoryDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("account_id",currentAccountId);
        queryWrapper.eq("production_dispatch_id",dispatchId);
        return list(queryWrapper);
    }

    @Override
    public List<VProductionWorkInventoryDetail> listByProductionWorkId(Long productionWorkMainId) {
        Integer currentAccountId = accountService.getCurrentAccountId();
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<VProductionWorkInventoryDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("account_id",currentAccountId);
        queryWrapper.eq("production_work_main_id",productionWorkMainId);
        return list(queryWrapper);
    }

    @Override
    public List<UnExecutedBo> getUnExecuteQuantity(String inventoryIds,String warehouseIds) {
        Integer currentAccountId = accountService.getCurrentAccountId();
        UserInfo userInfo = UserThreadLocal.get();
        return baseMapper.getUnExecuteQuantityList(userInfo.getCompanyId(), currentAccountId, inventoryIds ,warehouseIds);
    }

    @Override
    public void deleteFromMainId(Long mainId) {
        /** TODO 校验 是否 领料*/
        Integer currentAccountId = accountService.getCurrentAccountId();
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<VProductionWorkInventoryDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("account_id",currentAccountId);
        queryWrapper.eq("production_work_main_id",mainId);
        remove(queryWrapper);
    }
}
